// Copyright (c) 2021 Presto Labs Pte. Ltd.
// Author: daniel

#include "coin2/exchange/gopax/api_order/native_rest_async_asio_subscriber.h"

#include <glog/logging.h>

#include "coin2/base/time.h"
#include "coin2/exchange/gopax/api_order/native_private_client.h"
#include "coin2/exchange/order/gopax.pb.h"

namespace coin2::exchange::gopax::api_order {

void GopaxRestAsyncAsioSubscriber::QueryBalance() {
  auto http_context = rest_client()->QueryAccountBalance(RestParams{});
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&GopaxRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void GopaxRestAsyncAsioSubscriber::QueryAllOrders() {
  auto http_context = rest_client()->QueryAllOrders(RestParams{});
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&GopaxRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void GopaxRestAsyncAsioSubscriber::QueryFills() {
  auto http_context = rest_client()->QueryTrades(RestParams{});
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&GopaxRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void GopaxRestAsyncAsioSubscriber::QueryTransfer() {
  auto http_context = rest_client()->QueryTransfer(RestParams{});
  if (!http_context) {
    return;
  }
  http_context->handler =
      std::bind(&GopaxRestAsyncAsioSubscriber::HandleQuery, this, std::placeholders::_1);
  http_driver_->PostAsyncContext(http_context);
}

void GopaxRestAsyncAsioSubscriber::SubscribeAsync() {
  AddPeriodicTask(
      std::bind(&GopaxRestAsyncAsioSubscriber::QueryBalance, this),
      config_.query_account_balance_period_sec(),
      "query_balance");
  AddPeriodicTask(
      std::bind(&GopaxRestAsyncAsioSubscriber::QueryAllOrders, this),
      config_.query_open_orders_period_sec(),
      "query_all_orders");
  AddPeriodicTask(
      std::bind(&GopaxRestAsyncAsioSubscriber::QueryFills, this),
      config_.query_fill_period_sec(),
      "query_fills");
}

}  // namespace coin2::exchange::gopax::api_order
